package com.uzai.console.service.pdd.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.DateUtil;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.component.excel.template.PddPunishOrderExcelDemo;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.ConfigPlanMapper;
import com.uzai.console.mapper.PddOrderMapper;
import com.uzai.console.mapper.SysPluginMapper;
import com.uzai.console.mapper.UserAccDetailMapper;
import com.uzai.console.service.cms.CmsParamReplaceService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.pdd.PddPunishOrderService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 拼多多处罚订单
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PddPunishOrderServiceImpl implements PddPunishOrderService {

    Logger logger = LoggerFactory.getLogger(PddPunishOrderServiceImpl.class);

    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private CmsParamReplaceService cmsParamReplaceService;

    /**
     * 上传拼多多处罚订单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pddPunishOrderExcelDemoList
     * @return null
     */
    public void uploadPddPunishOrderFile(List<PddPunishOrderExcelDemo> pddPunishOrderExcelDemoList, Long merId){

        Integer now = DateUtil.getTime();

        //发送回复消息延迟
        int delay = 0;

        if(pddPunishOrderExcelDemoList != null && pddPunishOrderExcelDemoList.size() > 0){
            for (PddPunishOrderExcelDemo pddPunishOrderExcelDemo : pddPunishOrderExcelDemoList){
                try {

                    String childOrderNo = Tools.getStr(pddPunishOrderExcelDemo.getChildOrderNo());

                    // 查询订单是否存在
                    PddOrder pddOrder = pddOrderMapper.selectByChildOrderNo(childOrderNo, merId);
                    //查询到该订单，才做处理
                    if(pddOrder != null){
                        //不是处罚订单时才处理
                        if(pddOrder.getStatus().intValue() != OrderStatusEnum.STATUS_PUNISH.getValue().intValue()){
                            //订单处于结算状态，且 已返利，需要追回返利-扣款
                            if(pddOrder.getStatus().intValue() == 1 && pddOrder.getReStatus().intValue() ==1 ){
                                //判断是否已经有扣款明细，如果有，则跳过去
                                UserAccDetailQuery userAccDetailQuery = new UserAccDetailQuery();
                                userAccDetailQuery.setMerId(pddOrder.getMerId());
                                userAccDetailQuery.setType(AccDetailTypeEnum.PUB_ORDER_SUB.getValue());
                                userAccDetailQuery.setOrderId(pddOrder.getChildOrderNo());
                                List<UserAccDetail> userAccDetailList = userAccDetailMapper.findByList(userAccDetailQuery);
                                //还未产生扣款明细则新增加，如果有了就跳过不新增
                                if(userAccDetailList == null || userAccDetailList.size() == 0){
                                    //用户返利
                                    double reUserBal = pddOrder.getReUserBal();
                                    //上级返利
                                    double reParentUserBal = pddOrder.getReParentBal();
                                    //上上级返利
                                    double reSlParentUserBal = pddOrder.getReSlParentBal();
                                    //代理返利
                                    double reAgentBal = pddOrder.getReAgentBal();
                                    //上级代理返利
                                    double reSlAgentBal = pddOrder.getReSlAgentBal();
                                    //合伙人返利
                                    double rePartnerBal = pddOrder.getRePartnerBal();

                                    String tradeNo = pddOrder.getParentOrderNo() + "_" + pddOrder.getChildOrderNo();

                                    //查询用户信息
                                    User user = userService.findUserInfo(pddOrder.getUserId(), pddOrder.getDeviceType(), pddOrder.getMerId());
                                    if (user != null){
                                        //扣款用户返利
                                        updateBalance(reUserBal,0, now, user, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(),0l, pddOrder.getDeviceUniqueId(), tradeNo);

                                        //上级返利
                                        User parentUser = userService.findUserInfo(user.getParentId(), user.getDeviceType(), pddOrder.getMerId());
                                        if(parentUser != null){
                                            //扣款上级返利
                                            updateBalance(reParentUserBal,0, now, parentUser, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(), user.getId(), pddOrder.getDeviceUniqueId(), tradeNo);

                                            //上上级返利
                                            User slParentUser = userService.findUserInfo(parentUser.getParentId(), user.getDeviceType(), pddOrder.getMerId());
                                            if(slParentUser != null){
                                                //扣款上上级返利
                                                updateBalance(reSlParentUserBal,0, now, slParentUser, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(), user.getId(), pddOrder.getDeviceUniqueId(), tradeNo);
                                            }
                                        }

                                        //代理人返利
                                        User reAgenter = userService.findUserInfo(user.getAgentId(), user.getDeviceType(), pddOrder.getMerId());
                                        if(reAgenter != null ){
                                            //扣款代理人返利
                                            updateBalance(reAgentBal,0, now, reAgenter, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(), user.getId(), pddOrder.getDeviceUniqueId(), tradeNo);

                                            //上级代理人返利
                                            User slAgenter = userService.findUserInfo(reAgenter.getAgentId(), user.getDeviceType(), pddOrder.getMerId());
                                            if(slAgenter != null){
                                                //扣款上级代理返利
                                                updateBalance(reSlAgentBal,0, now, slAgenter, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(), user.getId(), pddOrder.getDeviceUniqueId(), tradeNo);
                                            }
                                        }

                                        //合伙人返利
                                        User partner = userService.findUserInfo(user.getPartnerId(), user.getDeviceType(), pddOrder.getMerId());
                                        if(partner != null){
                                            //扣款上级代理返利
                                            updateBalance(rePartnerBal,0, now, partner, AccDetailTypeEnum.PUB_ORDER_SUB.getValue(), pddOrder.getChildOrderNo(), user.getId(), pddOrder.getDeviceUniqueId(), tradeNo);
                                        }

                                        //发送订单维权回复消息
                                        sendMsgForPunishOrder(user, pddOrder, delay);
                                        delay = delay + 1;//每条消息延后1秒发送
                                    }
                                }

                                //修改订单状态维权
                                PddOrder pddOrder_old = new PddOrder();
                                pddOrder_old.setId(pddOrder.getId());
                                pddOrder_old.setMerId(pddOrder.getMerId());
                                pddOrder_old.setStatus(OrderStatusEnum.STATUS_PUNISH.getValue());
                                pddOrder_old.setReStatus(OrderReStatusEnum.RE_STATUS_BACK.getValue());
                                pddOrder_old.setUpdateTime(now);
                                pddOrder_old.setCommission(0.00D);
                                pddOrder_old.setCommissionRate(0.00D);
                                pddOrder_old.setProfit(0.00D);
                                pddOrder_old.setReUserBal(0.00D);
                                pddOrder_old.setReUserInte(0);
                                pddOrder_old.setReParentBal(0.00D);
                                pddOrder_old.setReAgentBal(0.00D);
                                pddOrder_old.setRePartnerBal(0.00D);
                                pddOrder_old.setReSlParentBal(0.00D);
                                pddOrder_old.setReSlAgentBal(0.00D);
                                pddOrder_old.setReOtherBal(0.00D);
                                pddOrderMapper.updatePunishInfo(pddOrder_old);

                            }else{
                                // 订单未返利
                                // /修改订单状态维权
                                PddOrder pddOrder_old = new PddOrder();
                                pddOrder_old.setId(pddOrder.getId());
                                pddOrder_old.setMerId(pddOrder.getMerId());
                                pddOrder_old.setStatus(OrderStatusEnum.STATUS_PUNISH.getValue());
                                pddOrder_old.setReStatus(OrderReStatusEnum.RE_STATUS_NO.getValue());
                                pddOrder_old.setUpdateTime(now);
                                pddOrder_old.setCommission(0.00D);
                                pddOrder_old.setCommissionRate(0.00D);
                                pddOrder_old.setProfit(0.00D);
                                pddOrder_old.setReUserBal(0.00D);
                                pddOrder_old.setReUserInte(0);
                                pddOrder_old.setReParentBal(0.00D);
                                pddOrder_old.setReAgentBal(0.00D);
                                pddOrder_old.setRePartnerBal(0.00D);
                                pddOrder_old.setReSlParentBal(0.00D);
                                pddOrder_old.setReSlAgentBal(0.00D);
                                pddOrder_old.setReOtherBal(0.00D);
                                pddOrderMapper.updatePunishInfo(pddOrder_old);
                            }
                        }
                    }

                } catch (Exception e) {
                    logger.error("add pdd punish order err:", e.getMessage());
                }
            }
        }
    }

    /**
     * 处理拼多多处罚订单业务功能
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param nowUser
     * @return null
     */
    private void updateBalance(double newBalance,int integral, int now, User nowUser,int awardType, String orderNo, Long sourceId, Long deviceUniqueId, String tradeno) {
        User user = new User();
        user.setId(nowUser.getId());
        user.setMerId(nowUser.getMerId());
        user.setDeviceType(nowUser.getDeviceType());
        user.setUpdateTime(now);
        user.setVersion(nowUser.getVersion());
        user.setBalance(Math.sub(nowUser.getBalance(), newBalance));
        user.setIntegral(nowUser.getIntegral() + integral);
        int count = userService.updateBalance(user);
        if (count==0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        UserAccDetail dub = new UserAccDetail();
        dub.setId(IdWorker.getId());
        dub.setTradeno(tradeno);
        dub.setMerId(nowUser.getMerId());
        dub.setUserId(nowUser.getId());
        dub.setDeviceUniqueId(deviceUniqueId);
        dub.setDeviceType(nowUser.getDeviceType());
        dub.setChangeInte(integral);
        dub.setChangeBal(0-newBalance); //扣除变动金额就是负数
        dub.setNewInte(nowUser.getIntegral());
        dub.setNewBal(user.getBalance());
        dub.setType(awardType);
        dub.setOrderId(orderNo);
        dub.setSourceUserId(sourceId);
        dub.setCreateTime(now);
        dub.setUpdateTime(now);

        //插入用户账户明细记录
        int insert = userAccDetailMapper.insert(dub);
        if(insert!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号入账明细失败");
        }

    }

    /**
     * 拼多多订单维权发送消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param user
     * @param pddOrder
     * @return null
     */
    private void sendMsgForPunishOrder(User user, PddOrder pddOrder, int delay){
        //如果提现记录的机器人不存在，则取会员默认客户端机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
        if(device != null){
            ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
            if(configPlan != null){
                //发送提现审核成功文本消息
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getPddId(), configPlan.getMerId());
                if(sysPlugin != null){
                    //发送提现审核成功文本消息
                    JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                    if(jsonObject != null){
                        //拼多多处罚订单回复买家
                        String message = jsonObject.getString("punish_reply_buyer");
                        if(StringUtils.isNotBlank(message)){
                            message = message.replace("[昵称]", Tools.getStr(user.getNickName()));
                            message = message.replace("[商品标题]", Tools.getStr(pddOrder.getTitle()));
                            message = message.replace("[订单编号]", Tools.getStr(pddOrder.getChildOrderNo()));
                            message = message.replace("[付款金额]", String.valueOf(Tools.getDouble(pddOrder.getPayment())));
                            message = message.replace("[收回金额]", String.valueOf(Tools.getDouble(pddOrder.getReUserBal())));
                            message = message.replace("[收回积分]", String.valueOf(Tools.getInteger(pddOrder.getReUserInte())));
                            message = message.replace("[账户余额]", String.valueOf(Tools.getDouble(user.getBalance())));
                            String cmsGoodListUrl = cmsParamReplaceService.getCmsGoodListUrl(pddOrder.getMerId(), user.getId(), user.getDeviceUniqueId());
                            message = message.replace("[订单列表]", Tools.getStr(cmsGoodListUrl));

                            //发送MQ消息
                            MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                            NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                            msgDto.setContent(noticeMsgDto);
                            msgDto.setId(IdWorker.getId());
                            msgDto.setDeviceType(device.getRecvmsgType());
                            msgDto.setDeviceUniqueId(device.getId());
                            msgDto.setMerId(pddOrder.getMerId());
                            msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                            noticeMsgDto.setContent(message);
                            noticeMsgDto.setBizUserId(user.getBizUserId());
                            noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                            noticeMsgDto.setGroupId(null);
                            noticeMsgDto.setNickName(user.getNickName());
                            noticeMsgDto.setMsgSource(1);
                            noticeMsgDto.setDelay(delay);
                            noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                            noticeMsgPushProducerService.sendMessage(msgDto);

                            logger.info("发送拼多多订单维权回复消息，para={}", JSONObject.toJSONString(msgDto));

                        }
                    }
                }
            }
        }
    }



}
